package com.criticalbotch.enjinapi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.net.URL;

public class EnjinAPI {
	
	String baseURL;	//! Website URL, such as site.enjin.com
	
	UserManager userManager = new UserManager();
	
	//get-tags
	//get-users
	//get-tags/user/xxx
	//get-tags/character/xxx
	//get-users/tag/xxx
	
	public void apiUsersToFile()
	{		
		try
		{
			BufferedReader in = new BufferedReader(new InputStreamReader(getUserURL().openStream()));
			BufferedWriter out = new BufferedWriter( new FileWriter(new File("get-users.json")));
			out.write(in.readLine());
			in.close();
			out.close();			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void getUsers()
	{
		apiUsersToFile();
		
		try
		{
			BufferedReader in = new BufferedReader(new FileReader( new File("get-users.json")));
			String JSON = in.readLine();
			
			UserManager userMan = getUserManager();
			
			userMan.addUsers(JSON);
			in.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public EnjinUser getUser(String name)
	{
		UserManager userMan = getUserManager();
		return userMan.getUser(name);
	}
	
	public EnjinUser getUser(int id)
	{
		UserManager userMan = getUserManager();
		return userMan.getUser(id);
	}
	
	public UserManager getUserManager()
	{
		return userManager;
	}
	
	//! Set the website URL
	public void setBaseURL(String url)
	{
		baseURL = url;
	}
	
	//! Get the website URL, with http:// added if not already present
	public String getBaseURL()
	{
		return baseURL;
	}
	
	public String getSafeBaseURL()
	{
		if(getBaseURL().startsWith("http://"))
			return getBaseURL();
		else
			return "http://"+getBaseURL();
	}
	
	public URL getUserURL() throws Exception
	{
		return new URL(getSafeBaseURL()+"/api/get-users");
	}
	
	public URL getTagURL() throws Exception
	{
		return new URL(getSafeBaseURL()+"/api/get-tags");		
	}
}
